﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using HU8.Helpers.Files;
using HU8.Helpers.Base;
using XMK.Tadong.Biz;
using XMK.Tadong.Model;
using System.Web.SessionState;
using System.Configuration;


namespace HU8.Web.FileExplorer.FileExplorer.WebServices
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : IHttpHandler, IRequiresSessionState 
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                FileExplorerConfig config = new FileExplorerConfig(context.Server, context);

                string path = context.Request["path"].ToString();//spaceType
                string DiskPath = ConfigurationManager.AppSettings["DiskPath"];//@"D:/TaDongDoc/";
                //"individual" "group" "project"
                string strSpaceType = context.Request["spaceType"].ToString();
                path = Microsoft.JScript.GlobalObject.decodeURI(path);
                if (string.IsNullOrEmpty(path))
                {
                    path = "~/";
                }

                string model_path = context.Session["sub_path"] + path.Replace("~/", "") ;
                if (model_path.EndsWith("/"))
                {
                    model_path = model_path.Substring(0, model_path.Length - 1);
                }

                path = path.Replace("~/", config.FilesPath);

                int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
                int chunks = context.Request["chunks"] != null ? int.Parse(context.Request["chunks"]) : 0;
                string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;

                HttpPostedFile fileUpload = context.Request.Files[0];
                //文件夹按照日期创建
                string FolderNmae = System.DateTime.Now.ToString("yyyyMMdd");
                string FolderID = path;
                
                var uploadPath = config.FilesPath + FolderNmae + "/";// context.Server.MapPath(path);
                


                string userId = context.Request.Cookies["user_id"].Value.ToString();
                //文件上传路径
                uploadPath = uploadPath.Replace(userId + "/", "");
                string team_id = context.Request.Cookies["team_id"].Value;
                if (!string.IsNullOrEmpty(team_id))
                {
                    uploadPath = uploadPath.Replace(team_id + "/", "");
                }
                string save_path = uploadPath; //存放路径

                save_path = save_path.Replace(DiskPath, "");

                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);

                //重命名文件
                string NewFileName = System.DateTime.Now.ToString("yyyyMMddhhmmss") + fileName.Substring(fileName.LastIndexOf('.'));


                
                if (chunk == 0)
                {
                    context.Session["tmpTime"] = DateTime.Now.ToFileTimeUtc() + fileName.Substring(fileName.LastIndexOf('.'));

                    //if (File.Exists(Path.Combine(uploadPath, fileName)))
                    //{
                    //    context.Session["isExist"] = true;
                    //    context.Session["tmpTime"] = DateTime.Now.ToFileTimeUtc();
                    //}
                    //else
                    //    context.Session["isExist"] = false;
                }

                //if (Convert.ToBoolean(context.Session["isExist"]))
                //{

                //    {
                //        if (fileName.Contains("."))
                //        {
                //            fileName = fileName.Replace(".", "_" + context.Session["tmpTime"].ToString() + ".");
                //        }
                //        else
                //        {
                //            fileName += "_" + context.Session["tmpTime"].ToString();
                //        }
                //    }
                //}


                context.Session["chunk_buffer_size"] = fileUpload.InputStream.Length;
                using (var fs = new FileStream(Path.Combine(uploadPath, context.Session["tmpTime"].ToString()), chunk == 0 ? FileMode.Create : FileMode.Append))
                {
                    var buffer = new byte[fileUpload.InputStream.Length];
                    fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                    fs.Write(buffer, 0, buffer.Length);
                }



                save_path = save_path + context.Session["tmpTime"].ToString();

                //文档类型 

                string suffix = fileName.Substring(fileName.LastIndexOf('.') + 1);
                string type = suffix;
                //string suffix1 = fileName.Substring(fileName.IndexOf('.'));
                //if (!String.IsNullOrEmpty(suffix))
                //{
                //    EXTBiz biz = new EXTBiz();
                //    ExtTypeinfo extmode = biz.getExtCodeByExtent(suffix.ToLower());
                //    type = extmode.EXT_CODE;
                    //switch (suffix.ToLower())
                    //{
                    //    case "jpg":
                    //    case "png":
                    //    case "bmp":
                    //        type = 1;
                    //        break;
                    //    case "doc":
                    //    case "docx":
                    //        type = 2;
                    //        break;
                    //    case "xls":
                    //    case "xlsx":
                    //        type = 3;
                    //        break;
                    //    case "pdf":
                    //        type = 4;
                    //        break;
                    //    case "txt":
                    //        type = 5;
                    //        break;
                    //    case "pptx":
                    //    case "ppt":
                    //        type = 6;
                    //        break;
                    //}
                //}
               
                     
                if (chunk == chunks - 1)
                {
                    //2097152==2M 默认一次大小
                    string fileSize = "";
                    int bSize = Convert.ToInt32(context.Session["chunk_buffer_size"] ) * (chunks - 1) + context.Request.ContentLength;
                    int kSize = bSize/1024;
                    if (kSize == 0)
                    { kSize = 1; }
                    if (kSize < 1024)
                    {
                        fileSize = kSize.ToString() + "K";
                    }
                    else
                    {
                        int mSize = kSize / 1024 + 1;
                        fileSize = mSize.ToString() + "M";

                    }

                    if (strSpaceType == "individual")
                    {
                        TB_PERSON_FILEBiz fileBiz = new TB_PERSON_FILEBiz();
                        //if (fileBiz.HasFileName(userId, fileName, FolderID))
                        //{
                        //    fileName = Path.GetFileNameWithoutExtension(fileName);
                        //    fileName = fileName + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "." + suffix;
                        //}
                        TB_PERSON_FILEInfo fileObj = new TB_PERSON_FILEInfo();
                        fileObj.USER_ID = context.Request.Cookies["user_id"].Value;
                        fileObj.FILE_NAME = fileName;    //文件名
                        //fileObj.CREATE_TIME = ; //创建时间
                        fileObj.SAVE_PATH = save_path; //存放路径
                        //fileObj.WDLX =//文档类型 1-Picture  2-Word  3-Excel  4-Pdf  5-Txt  6-Ppt 0-未知
                        fileObj.FILE_EXT = type;
                        //文件大小
                        fileObj.FILE_SIZE = fileSize;
                        fileObj.FOLDER_ID = FolderID;
                        //文件版本
                        fileObj.FILE_VERSION = fileBiz.GetMaxFileVersion(fileObj.FILE_NAME,userId)+1;
                        
                        fileBiz.Upload(fileObj);

                    }
                    else if (strSpaceType == "group")
                    {
                        TB_TEAM_FILEInfo fileObj = new TB_TEAM_FILEInfo();
                        TB_TEAM_FILEBiz fileBiz = new TB_TEAM_FILEBiz();
                        //if (fileBiz.HasFileName(userId, context.Request["groupId"], fileName, FolderID))
                        //{
                        //    fileName = Path.GetFileNameWithoutExtension(fileName);
                        //    fileName = fileName + System.DateTime.Now.ToString("yyyyMMddhhmmss") + "." + suffix;
                        //}
                        fileObj.STATUS = 1;
                        fileObj.FILE_EXT = type;
                        fileObj.SAVE_PATH = save_path;
                        fileObj.FILE_NAME = fileName;
                        fileObj.FILE_SIZE = fileSize;
                        fileObj.USER_ID = context.Request.Cookies["user_id"].Value;
                        fileObj.TEAM_ID = Convert.ToInt32(context.Request["groupId"]);
                        fileObj.FOLDER_ID = FolderID;
                        //文件版本
                        fileObj.FILE_VERSION = fileBiz.GetMaxFileTeam(fileName, context.Request["groupId"]) + 1;
                        fileBiz.Add(fileObj);
                        ////插入日志
                        //string ip = context.Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : context.Request.ServerVariables["REMOTE_ADDR"];
                        //XMKLogBiz.WriteLogFile(LogOperateType.DeleteFile, fileObj.FILE_NAME, fileObj.FILE_ID, "20",ip);
                        

                    }
                    else if (strSpaceType == "project")
                    {
                        //TB_XMK_FILEInfo fileObj = new TB_XMK_FILEInfo();
                        //Tb_Xmk_FileBiz fileBiz = new Tb_Xmk_FileBiz();

                        //fileObj.FILE_NAME = fileName;
                        //fileObj.FILE_SIZE = fileSize;
                        //fileObj.STATUS = 0;
                        //fileObj.FOLDER_ID = Convert.ToUInt32(save_path);
                        //fileBiz.Upload(fileObj);
                    }
                }







                //如果正确继续执行，错误则抛出异常
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"result\" : \"Success\", \"id\" : \"id\"}");
            }
            catch (System.Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 102, \"message\":" + ex.Message + "\"}, \"id\" : \"id\"}");
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }

    }
}